﻿using Cysharp.Threading.Tasks;
using System;
using System.Collections;
using UnityEngine.SceneManagement;
using YooAsset;
using YooAssetHandle = YooAsset.AssetHandle;

namespace MFramework
{
    public class ResourcesManager
    {
        public static void Initialize(Action callback)
        {
            YooAssets.Initialize();
            var package = YooAssets.CreatePackage("DefaultPackage");
            YooAssets.SetDefaultPackage(package);
#if UNITY_EDITOR
            var initParameters = new EditorSimulateModeParameters();
            var simulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild(EDefaultBuildPipeline.BuiltinBuildPipeline, "DefaultPackage");
            initParameters.SimulateManifestFilePath = simulateManifestFilePath;
#else
            var initParameters = new OfflinePlayModeParameters();
#endif
            var operation = package.InitializeAsync(initParameters);
            operation.Completed += (AsyncOperationBase _) =>
            {
                callback?.Invoke();
            };
        }

        public static AssetHandle LoadAsset<T>(string path) where T : UnityEngine.Object
        {
            AssetHandle handle = new AssetHandle();
            handle.Init(YooAssets.LoadAssetSync<T>(path));
            return handle;
        }

        public static AssetHandle LoadAssetAsync<T>(string path) where T : UnityEngine.Object
        {
            AssetHandle handle = new AssetHandle();
            handle.Init(YooAssets.LoadAssetAsync<T>(path));
            return handle;
        }

        public static void UnloadUnusedAssets()
        {
            var package = YooAssets.GetPackage("DefaultPackage");
            package.UnloadUnusedAssets();
        }

        public static void TryUnloadUnusedAsset(string path)
        {
            var package = YooAssets.GetPackage("DefaultPackage");
            package.TryUnloadUnusedAsset(path);
        }

        public static SceneHandle LoadSceneAsync(string path, LoadSceneMode sceneMode = LoadSceneMode.Single, bool suspendLoad = false)
        {
            SceneHandle sceneHandle = new SceneHandle();
            sceneHandle.Init(YooAssets.LoadSceneAsync(path, sceneMode, suspendLoad));
            return sceneHandle;
        }
    }
}
